#include"list.h"

ListNode* BuyNode(LTDataType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}

	node->_data = x;
	node->_next = NULL;
	node->_prev = NULL;

	return node;
}

ListNode* ListCreate()
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (!node)
	{
		perror("malloc fail:");
		exit(-1);
	}

	node->_next = node;
	node->_prev = node;

	return node;
}

void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->_next;
	while (cur != pHead)
	{
		ListNode* tmp = cur->_next;
		free(cur);
		cur = tmp;
	}

	free(pHead);
}

void ListPrint(ListNode* pHead)
{
	ListNode* cur = pHead->_next;
	printf("pHead<=>");
	while (cur != pHead)
	{
		printf("%d<=>", cur->_data);
		cur = cur->_next;
	}
	printf("\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	//ListInsert(pHead, x);
	ListNode* newnode = BuyNode(x);

	pHead->_prev->_next = newnode;
	newnode->_prev=pHead->_prev;
	newnode->_next = pHead;
	pHead->_prev = newnode;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	//ListErase(pHead->_prev);
	if (pHead->_prev != pHead)
	{
		ListNode* tmp = pHead->_prev;
		pHead->_prev = tmp->_prev;
		tmp->_prev->_next = pHead;
		free(tmp);
		tmp = NULL;
	}
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	//ListInsert(pHead->_next, x);
	ListNode* newnode = BuyNode(x);
	newnode->_next=pHead->_next;
	newnode->_prev = pHead;
	pHead->_next->_prev = newnode;
	pHead->_next = newnode;
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	//ListErase(pHead->_next);
	if (pHead->_next != pHead)
	{
		ListNode* node = pHead->_next;
		node->_next->_prev = pHead;
		pHead->_next = node->_next;
		free(node);
		node = NULL;
	}
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);

	ListNode* cur = pHead->_next;
	while (cur != pHead)
	{
		if (cur->_data == x)
			return cur;
		cur = cur->_next;
	}

	return NULL;

}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);

	ListNode* newnode = BuyNode(x);
	ListNode* dist = pos->_prev;

	dist->_next = newnode;
	newnode->_prev = dist;
	newnode->_next = pos;
	pos->_prev = newnode;
	
}

void ListErase(ListNode* pos)
{
	assert(pos);

	ListNode* posPrev = pos->_prev;
	ListNode* posNext = pos->_next;

	posPrev->_next = posNext;
	posNext->_prev = posPrev;
	free(pos);
}
